import React, { useEffect, useState } from 'react'
import { Button, Table, message } from 'antd';
import axios from 'axios';

export default function Draft(props) {
  const [news, setNews] = useState([])
  // 获取个人用户的新闻数据
  const { username } = JSON.parse(localStorage.getItem('token'))
  useEffect(() => {
    axios.get(`/news?author=${username}&auditState=0&_expand=category`).then(res => {
      console.log(res.data)
      setNews(res.data)
    })
  }, [username])

  // 删除新闻
  const deleteNew = (item) => {
    // console.log(item)
    setNews(news.filter(data => data.id !== item.id))
    axios.delete(`/news/${item.id}`)
  }

  // 上传审核
  const handleCheck = (item) => {
    axios.patch(`/news/${item.id}`, {
      auditState: 1
    }).then(res => {
      message.info(`前往审核中查看你的新闻`)
      props.history.push('/audit-manage/list')
    })
  }

  // 表格数据
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      key: 'title',
      render: (title, item) => <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (item) => item.title
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button type='primary' danger onClick={() => deleteNew(item)}>删除</Button>
          <Button type='primary' onClick={() => props.history.push(`/news-manage/update/${item.id}`)}>编辑</Button>
          <Button type='primary' ghost onClick={() => handleCheck(item)}>上传</Button>
        </div>
      }
    },
  ];
  return (
    <div>
      <Table dataSource={news} columns={columns} rowKey={item => item.id} pagination={{ pageSize: 5 }} />;
    </div>
  )
}
